package com.leung.machine.stateListener;


import com.leung.machine.action.StateAction;
import com.leung.machine.enums.Events;
import com.leung.machine.enums.States;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.state.State;

import java.util.Map;

/**
 * @author 丨一
 * @version 1.0
 * @title OrderStateMachineListener
 * @description:
 * @date 2025/10/7 上午9:40
 */
public class OrderStateMachineListener extends StateMachineListenerAdapter<States, Events> {

    private final Map<States, StateAction> actionMap;


    public OrderStateMachineListener(Map<States, StateAction> actionMap) {
        this.actionMap = actionMap;
    }

    @Override
    public void stateContext(StateContext<States, Events> context) {
        if (context.getStage() == StateContext.Stage.STATE_CHANGED) {
            State<States, Events> to = context.getTarget();
            if (to != null && actionMap.containsKey(to.getId())) {
                StateAction action = actionMap.get(to.getId());
                StateAction.DynamicContext dynamicContext = context.getExtendedState().get("context", StateAction.DynamicContext.class);
                action.execute(dynamicContext);
            }
        }
    }
}
